package edu.pku.sei.modeler.actions;

import java.util.HashMap;
import java.util.Iterator;

import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaLink;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.structure.MetaShapeElement;

public class DeleteMetaElementCommand extends Command {
	private MetaShapeElement element;

	public DeleteMetaElementCommand(MetaShapeElement element) {
		this.element = element;
	}

	@Override
	public boolean canExecute() {
		return true;
	}

	@Override
	public boolean canUndo() {
		// TODO Auto-generated method stub
		return super.canUndo();
	}

	@Override
	public void execute() {
		if (element instanceof MetaNode) {
			try {
				deleteNode((MetaNode)element);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FactoryNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private void deleteNode(MetaNode node) throws IllegalArgumentException, FactoryNotFoundException {
		MetaDiagram diagram = node.getDiagram();
		int index = diagram.getNodes().indexOf(node);
		diagram.getNodes().remove(index);
		// There's always the possibility that this node has already been deleted by the
		// time this command is executed (eg., when the package containing this class
		// is also selected).  Hence, we check to see if the node exists in the diagram.
		// If not, do nothing.
		if (index == -1)
			return;
		HashMap incomingConnectionsToSource = new HashMap();
		HashMap outgoingConnectionsToTarget = new HashMap();
		for (Iterator iter = node.getIncomings().iterator(); iter.hasNext();) {
			MetaLink link = (MetaLink) iter.next();
			link.setTarget(null);
			MetaNode source = link.getSource();
			if(source != null) {
				source.getOutgoings().remove(link);
				link.setSource(null);
				incomingConnectionsToSource.put(link, source);
			}
		}
		for (Iterator iter = node.getOutgoings().iterator(); iter.hasNext();) {
			MetaLink link = (MetaLink) iter.next();
			link.setSource(null);
			MetaNode target = link.getTarget();
			if(target != null) {
				target.getIncomings().remove(link);
				link.setTarget(null);
				outgoingConnectionsToTarget.put(link, target);
			}
		}
		node.getIncomings().clear();
		node.getOutgoings().clear();
//		
//		MetaModelElement modelElement = node.getModelElement();
//		MetaModel model = node.getModel();
//		model.removeFromModel(modelElement);
//		ModelRegistry.getRegistry().getFactory(model).unRegisterFromPackage(modelElement);
		// TODO:remove from model
//		MetaModelingProject p = MetaModelerPlugin.getDefault().getProjectByDiagram(diagram);
//		p.removeFromModel(node.getElement(), diagram);
		
	}

	
}
